package ryanbrown.tictactoe.server;

import java.awt.BorderLayout;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import ryanbrown.tictactoe.TicTacToeConstants;

public class TicTacToeServer extends JFrame implements TicTacToeConstants{


	public static void main(String[] args) {
		TicTacToeServer frame = new TicTacToeServer();
	}

	public TicTacToeServer() {
		JTextArea jtaLog = new JTextArea();
		JScrollPane scrollPane = new JScrollPane(jtaLog);

		add(scrollPane, BorderLayout.CENTER);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setSize(300, 300);
		setTitle("TicTacToeServer");
		setVisible(true);

		try {
			ServerSocket serverSocket = new ServerSocket(8001);
			jtaLog.append(new Date() + ": Server started at socket 8000\n");

			int sessionNo = 1;

			while(true) {
				jtaLog.append(new Date() + ": Wait for players to join session " + sessionNo + "\n");

				// Connect to player 1
				Socket player1 = serverSocket.accept();

				jtaLog.append(new Date() + ": Player 1 joined session " + sessionNo + "\n");
				jtaLog.append("Player 1's IP address" + player1.getInetAddress().getHostAddress() + "\n");

				// Notify that the player is Player 1
				new DataOutputStream(player1.getOutputStream()).writeInt(PLAYER1);

				// Connect to player 2
				Socket player2 = serverSocket.accept();

				jtaLog.append(new Date() + ": Player 2 joined session " + sessionNo + "\n");
				jtaLog.append("Player 2's IP address" + player2.getInetAddress().getHostAddress() + "\n");

				// Notify that the player is Player 2
				new DataOutputStream(player2.getOutputStream()).writeInt(PLAYER2);

				// Display this session and increment session number
				jtaLog.append(new Date() + ": Start a thread for session " + sessionNo++ + "\n");

				// Create a new thread for this session of two players
				HandleASession task = new HandleASession(player1, player2);

				// Start the new thread
				new Thread(task).start();
			}
		}
		catch(IOException ex) {
			System.err.println(ex);
		}
	}
}